package com.suzhiliang.springbootlesson.securityOAuth2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Copyright (C), 2015-2019, XXX有限公司
 *
 * @ClassName: CustomLogoutSuccessHandler
 * @Author: xmm
 * @Date: 2019/7/23 10:20
 * @Description: 登出控制类
 *                  当我们退出系统时需要访问SpringSecrutiy的logout方法来清空对应的session信息，
 *                  那我们退出后改用户的access_token还依然存在那就危险了，
 *                  一旦别人知道该token就可以使用之前登录用户的权限来操作业务。
 * @Version 1.0
 */
@Component
public class CustomLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler implements LogoutSuccessHandler {

    private static final String BEARER_AUTHENTICATION = "Bearer";
    private static final String HEADER_AUTHENTICATION = "authentication";

    @Autowired
    private TokenStore tokenStore;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Authentication authentication)
            throws IOException, ServletException {

        String token= httpServletResponse.getHeader(HEADER_AUTHENTICATION);

        if(token!=null || token.startsWith(HEADER_AUTHENTICATION)){
            OAuth2AccessToken oAuth2AccessToken = tokenStore.readAccessToken(token.split(" ")[0]);
            if(oAuth2AccessToken!=null){
                tokenStore.removeAccessToken(oAuth2AccessToken);
            }
        }


    }
}
